//
//  YHKPublishViewController.swift
//  xinlangweiBo2
//
//  Created by 杨和逵 on 16/3/5.
//  Copyright © 2016年 yanghekui. All rights reserved.
//

import UIKit
import SnapKit

/*
1.分析界面
  标题
  占位文字
  键盘

2.分析功能
*/

let zhanWeiFu = "不要问我是谁，我叫隔壁老王"



class YHKPublishViewController: UIViewController ,UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    //记录约束
    var const:Constraint?

    
    override func viewDidLoad() {
        super.viewDidLoad()

     view.backgroundColor = UIColor.whiteColor()
        
        //设置导航栏中的控件
       setupNav()
        
        //设置textView
        setupTextView()
        
        //设置ToolBar
        setupToolBar()
        
        //照片collectionView
        setPhotoView()
        
        //对键盘的监听事件
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeToolBarFarme:", name:UIKeyboardWillChangeFrameNotification , object: nil)
//        UIKeyboardDidChangeFrameNotification
//        UIKeyboardWillChangeFrameNotification
        
        
        //对点击表情按钮进行监听
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "inputEmoticon:", name: kNotificaionEmoticonTransform, object: nil)
        
        
    }

    
    //监听方法的实现,输入框插入表情
  @objc private func inputEmoticon(noti:NSNotification){
    
    //先得获取表情
    let emoticon = noti.userInfo!["emoticon"] as! YHKEmoticonMdeol
    
    //显示图片
    if let png = emoticon.png {
        
        //把图片显示在 TextView
        //记录之前的，拿到之前的 attributedText
        //把他转成一个可选的
        let beforeAttributedText = NSMutableAttributedString(attributedString: textView.attributedText)
        
        //1.创建一个附件
        let attachement = YHKTextAttachment()
        attachement.emoticon = emoticon
        
        //2.设置图片
        let imagePath = "\(emoticon.path!)/\(png)"
        
        attachement.image = UIImage(named: imagePath)
        
        //3.赋值给Attribute
        let attribute = NSAttributedString(attachment: attachement)
        
        //插入到光标所在位置
        let range = textView.selectedRange
        
        beforeAttributedText.insertAttributedString(attribute, atIndex: range.location)
        
             print(textView.font)
             print(beforeAttributedText.length)
        
        beforeAttributedText.addAttributes([NSFontAttributeName: textView.font!], range: NSMakeRange(0, beforeAttributedText.length))
        
            textView.attributedText = beforeAttributedText
        
           //赋值之后修改光标的位置
        textView.selectedRange = NSMakeRange(range.location + 1,0)
        
    }
    
    
    //emoji
    if let emoji = emoticon.emoji{
        
        //先记录之前的attributeText
        let beforeAttribute = NSMutableAttributedString(attributedString:  textView.attributedText)
        
        let range = textView.selectedRange
        
        beforeAttribute.replaceCharactersInRange(NSMakeRange(range.location, 0), withString: emoji)
        
        textView.attributedText = beforeAttribute
    }
    
        
    }
    
    
    
    //MARK:--销毁通知
    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self, name: kNotificaionEmoticonTransform, object: nil)
        
    }
    
    
    
    //MARK:--键盘改变的通知
    func changeToolBarFarme(noti:NSNotification){
        
        
//        print(noti.userInfo)
        /*
        [UIKeyboardFrameBeginUserInfoKey: NSRect: {{0, 736}, {414, 226}}, UIKeyboardCenterEndUserInfoKey: NSPoint: {207, 849}, UIKeyboardBoundsUserInfoKey: NSRect: {{0, 0}, {414, 226}}, UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 736}, {414, 226}}, UIKeyboardAnimationDurationUserInfoKey: 0.25, UIKeyboardCenterBeginUserInfoKey: NSPoint: {207, 849}, UIKeyboardAnimationCurveUserInfoKey: 7, UIKeyboardIsLocalUserInfoKey: 1])
        
        
        
        [UIKeyboardFrameBeginUserInfoKey: NSRect: {{0, 465}, {414, 271}}, UIKeyboardCenterEndUserInfoKey: NSPoint: {207, 871.5}, UIKeyboardBoundsUserInfoKey: NSRect: {{0, 0}, {414, 271}}, UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 736}, {414, 271}}, UIKeyboardAnimationDurationUserInfoKey: 0.25, UIKeyboardCenterBeginUserInfoKey: NSPoint: {207, 600.5}, UIKeyboardAnimationCurveUserInfoKey: 7, UIKeyboardIsLocalUserInfoKey: 1])
        
        */
     
        if let info = noti.userInfo {
            
            //需要把NSRect 转成CGRect
            let endFrame = info[UIKeyboardFrameEndUserInfoKey]?.CGRectValue
            
            if endFrame?.origin.y == kUIScreenHeigth{
                print("我走了，不要想我")
                
                //更新约束
                toolBar.snp_updateConstraints(closure: { (make) -> Void in
                    
                    
                    self.const = make.bottom.equalTo(view.snp_bottom).constraint
         
                    
                })
                
                
            }else{
                print("亲，我来了")
                
                //更新约束
                toolBar.snp_updateConstraints(closure: { (make) -> Void in
                    
                    self.const = make.bottom.equalTo(view.snp_bottom).offset(-endFrame!.size.height).constraint//271键盘的高度
                })
                
                
                //给toolBar加一个动画效果，让他的键盘弹出的时间一致
                
                UIView.animateWithDuration(0, animations: { () -> Void in
                    
                //如果需要重新排布里面的子控件就需要使用这个方法
                 self.toolBar.layoutIfNeeded()
                })
                
              
            }
        }
        
    }
    
    
    

    ///设置导航栏中的控件
   private func setupNav(){
        //左
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
    
       //右
       navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "publish")
        //禁用右边item
    navigationItem.rightBarButtonItem?.enabled = false
    
    
    //中间的lable
    let titleLable = UILabel(frame: CGRectMake(0,0,200,44))
    
    titleLable.numberOfLines = 0
    
    titleLable.textAlignment = .Center
    
    let str = "发布微博\n\(YHKLoginModelView.shareInstance.model?.screen_name ?? "")"
    
    let attribute = NSMutableAttributedString(string: str)
    
    //添加属性
    //修改 发布微博 4个字的属性
    attribute.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(15)], range: NSMakeRange(0, 4))
    
    //修改 名字 的字属性
    attribute.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(13),NSForegroundColorAttributeName:UIColor.orangeColor()], range: NSMakeRange(4, str.characters.count - 4))
    
    titleLable.attributedText = attribute//赋值
    
    navigationItem.titleView = titleLable//添加到中间
        
    }

    //返回
   @objc private func dismiss(){
    
    dismissViewControllerAnimated(true) { () -> Void in
        
    }
    
    }
    
    //发布
   @objc private func publish(){}
    

    ///设置textView
    private func setupTextView(){
        
        //添加控件
        view.addSubview(textView)
        
        //设置约束
        textView.frame = view.frame
        
        textView.font = UIFont.systemFontOfSize(15)
        
        textView.holderString = zhanWeiFu
        
        //代理
        textView.delegate = self
  
        //滑动textView让，键盘消失=====人性化
        textView.alwaysBounceHorizontal = true
        textView.keyboardDismissMode = .OnDrag
        
        
    }
    
    
    //MARK:--照片的私有方法，添加控件和设置约束
    private func setPhotoView(){
        
        //添加到textView中
        textView.addSubview(photoView)
        
        //设置约束
        photoView.snp_makeConstraints { (make) -> Void in
            
            //中心  大小
            make.center.equalTo(textView.snp_center)
            make.height.equalTo(kUIScreenWidth - CGFloat(2*photoViewMargin))
            make.width.equalTo(kUIScreenWidth - CGFloat(2*photoViewMargin))
            
        }
        
        
    }
    
    
    
    //MARK:toolBar的背景颜色
    private func setupToolBar(){
    
        //修改toolBar的背景颜色
        toolBar.backgroundColor = UIColor.lightGrayColor()
        
        //定义一个数组存放图片的名称
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "choosePicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]

        //定义一个数值，来接受 items
        var items = [UIBarButtonItem]()
        
        
        
        //遍历数组
        for setting in itemSettings{
            
            //自定义button
            let button = UIButton(type: .Custom)
            
            //设置button的属性和方法
            button.setImage(UIImage(named: setting["imageName"]!), forState: .Normal)
            
            let imageName = setting["imageName"]!
            button.setImage(UIImage(named:"\(imageName)_highlighted" ), forState: UIControlState.Highlighted)
            
            //btn的大小
            button.sizeToFit()

            //添加方法
            if let action = setting["action"]{
                
                //当添加方法的时候===> “loadData” 这个并不是代表他的字符串而是一个方法，需要转换
                button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            }
            
            //赋值给
            let item = UIBarButtonItem(customView: button)
            
            //item 添加到toolbar  一定要自己定义一个数组
            items.append(item)
            
            //添加弹簧，让他们有间隔
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        
        //多了一个让它消失,最后一个
        items.removeLast()
        
        //赋值
        toolBar.items = items
        
        //添加视图的约束
        view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
         self.const = make.bottom.equalTo(view.snp_bottom).constraint
            
            //高
            make.height.equalTo(40)
        }
    
    }
    
    
    //MARK:--选择图片的方法
    @objc private func choosePicture(){
        
        //1.第一步，判断下，我们能否访问到手机的相册
        if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
        
        //2.如果可以，我们将进行页面的跳转
        let picker = UIImagePickerController()
            
        //3.访问的类型：相机、相册、保存的相册
        picker.sourceType = .PhotoLibrary
            
        //4.设置代理，实现将选中的图片保存在数组中
        picker.delegate = self
            
        //让方法就是一个动画效果，让框从底部出来
        presentViewController(picker, animated: true, completion: { () -> Void in
            
        })
        
        }
        
        
        
    }
    //MARK:--显示表情的方法
    @objc private func inputEmoticon(){
        
        print("显示表情")
        
        
        //1.注销第一响应者
        textView.resignFirstResponder()
        //2.判断inputView = nil 的时候，我们让显示表情，否者显示系统键盘
        if textView.inputView == nil {
            
            textView.inputView = emoticonView
        }else{
            
            textView.inputView = nil
        }
        
        //3.成为第一响应者
        textView.becomeFirstResponder()
        
    }
    

    
   //MARK:懒加载
    private lazy var textView:YHKTextView = YHKTextView()
    
    private lazy var toolBar:UIToolbar = UIToolbar()
    
    private lazy var photoView:YHKPhotoView = {
    
    let photoView = YHKPhotoView()
        
        //调用闭包
        photoView.closure = { [unowned self] () -> () in
            
            self.choosePicture()
            
        }
           return photoView
    }()
    
    //表情视图
    private lazy var emoticonView:YHKEmoticonView = {
    
    let emoticon = YHKEmoticonView()
        
        emoticon.backgroundColor = UIColor.yellowColor()

        
        emoticon.frame.size = CGSizeMake(kUIScreenWidth,217)
    return emoticon
    
    }()

    
    
    
    
    
    
}


//MARK:textView的代理方法
extension YHKPublishViewController{
    
    func textViewDidChange(textView: UITextView) {
        
        if textView.hasText() {
            
            //不显示占位符
            self.textView.holderString = ""
            
        } else {
            //显示占位符
            self.textView.holderString = zhanWeiFu
        }
        
        //需要重绘
        self.textView.setNeedsDisplay()
        
        //让发布按钮隐藏与显示
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
}


//MARK:--UIImagePickerControllerDelegate,UINavigationControllerDelegate
extension YHKPublishViewController{
    
//======注意========>>>>>>实现了代理方法，一定要调用 dismiss 方法，不调用的话，不能自动消失
    
    //为了拿到选中的图片====过期的方法，还可以用
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
    
        //图片拿到之后，不建议添加直接添加到数组中，因为图片很多地方用到了，很容易，混乱。直接设置一个方法，存放图片就行
        
        //调用方法，添加图片
        photoView.addImages(image)
        
        //实现dismiss方法
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
        
        print("来了")
    }

    
    //消失的时候调用的方法
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        
          print("走了")
        picker.dismissViewControllerAnimated(true) { () -> Void in
          
        }
    }
    
    
}

